#include "Main.h"
#include "Graphics.h"
#include "Animation.h"

#define MAGIC_NUMBER 0xBEB0

class ResourceManager{
//maybe later I'll do asynch file io.

	////HASH TABLES
	//Graphics
	OZBlock<string> ImageIDs;   ///IMAG 1229799751
	OZBlock<string> SpriteIDs;  ///SPRT 1414550100
	//Animation
	OZBlock<string> SheetIDs;   ///SHEE 1397245253
	//Physics
	//World
	//Input


	ResourceManager(){}
	void Initialize(){
	ImageIDs = OZBlock<string>(3);
	ModelIDs = OZBlock<string>(3);
	BoneIDs  = OZBlock<string>(3);
	AnimIDs  = OZBlock<string>(3);
	}

	unsigned int HASH(string s){
	string cpy = s; // we need to edit the string a bit.
	int len = cpy.size();
	cpy.append(0);cpy.append(0);cpy.append(0);cpy.append(0);//add 32 zero bits to the end
	unsigned int DataStream = (cpy[0]<<24)|(cpy[1]<<16)|(cpy[2]<<8)|(cpy[3]);
	unsigned int Polynomial = 79764919; //constant
	int Read=4;BYTE ReadBits=0;
	while(Read < len){
		if(DataStream & 2147483648){DataStream ^= Polynomial;}//XOR shift, if the last bit is one, the 2147483648 is just a one in the 31 bit slot
		DataStream<<1;
		DataStream |= (s[Read]&(1<<ReadBits)>>ReadBits); //add a bit to the stream
		ReadBits++;if(ReadBits >= 8){ReadBits-=8; Read++;}
		}
	return DataStream;
	}


	void Load(string Filename){
	int Header,Length;
	string c_Data;
	ifstream File(Filename.c_str(),ifstream::binary);
	if(!File.good()){MessageBoxA ( NULL,"Error Opening PNG", "Error Reading Image...", MB_OK );return;}
	File.read((char*)&Header,sizeof(int));
	//ENDIAN_SWAP(Sig);
	if(Header != MAGIC_NUMBER ){MessageBoxA ( NULL,"Invalid Entity File Identifyer.", "Loader Error", MB_OK );return;}
	while(File.good()){
	File.read((char*)&Header,sizeof(int));
	File.read((char*)&Length,sizeof(int));
	switch(Header){
	case 1229799751:{//Image
		int index;
		while(File.get() != '/"'){}
		while(File.peek() != '/"'){c_Data+=File.get();}
		if(ImageIDs[HASH(c_Data)]==NULL){
		index = ImageIDs.Add(&c_Data,Graphics::p_Graphics->Images.Add(new Image(),HASH(c_Data)));}
		Graphics::p_Graphics->Images[index]->Load(c_Data);break;}

	case 1414550100:{ //Sprite
		Location L;
		int index;
		File.Read((char*)&Location.Position.v[0],sizeof(Location));
		while(File.get() != '/"'){}
		while(File.peek() != '/"'){c_Data+=File.get();}
		if(ImageIDs[HASH(c_Data)]==NULL){
		index = ImageIDs.Add(&c_Data,Graphics::p_Graphics->Images.Add(new Image(),HASH(c_Data)));}
		Graphics::p_Graphics->Images[index]->Load(c_Data);
		SpriteIDs.Add(&c_Data
			,Graphics::p_Graphics->Sprites.Add(new Sprite(Graphics::p_Graphics->Images[index]));//give an ID
					break;}
	default:break;
			}
	c_Data.clear();
		}
	}

};